package com.datacenter.service;

import com.datacenter.entity.*;
import com.datacenter.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 趋势分析服务
 * 
 * 业务含义：
 * 实现场景2的9年历史数据趋势分析功能，包括：
 * - 资源增长趋势：年度新增接口/库表/Excel数量、各部门资源贡献占比
 * - 用户行为变化：季度下载量/调用量峰值、不同资源类型的使用偏好
 * - 热门资源排行：9年累计下载Top10、调用Top10
 */
@Slf4j
@Service
public class TrendAnalysisService {
    
    @Autowired
    private ResourceMetadataMapper resourceMetadataMapper;
    
    @Autowired
    private ApiCallLogMapper apiCallLogMapper;
    
    @Autowired
    private DownloadLogMapper downloadLogMapper;
    
    @Autowired
    private UserApplicationMapper userApplicationMapper;
    
    /**
     * 获取资源增长趋势分析
     * 业务含义：分析2015.05-2024.04期间资源增长趋势，按年度和部门统计
     */
    public Map<String, Object> getResourceGrowthTrend() {
        log.info("开始分析资源增长趋势");
        
        Map<String, Object> trendData = new HashMap<>();
        
        // 年度新增资源统计
        List<Map<String, Object>> yearlyGrowth = getYearlyResourceGrowth();
        trendData.put("yearlyGrowth", yearlyGrowth);
        
        // 各部门资源贡献占比
        List<Map<String, Object>> departmentContribution = getDepartmentContribution();
        trendData.put("departmentContribution", departmentContribution);
        
        // 资源类型增长趋势
        List<Map<String, Object>> resourceTypeTrend = getResourceTypeTrend();
        trendData.put("resourceTypeTrend", resourceTypeTrend);
        
        log.info("资源增长趋势分析完成");
        return trendData;
    }
    
    /**
     * 获取用户行为变化分析
     * 业务含义：分析用户使用行为的变化趋势，包括下载量和调用量峰值
     */
    public Map<String, Object> getUserBehaviorTrend() {
        log.info("开始分析用户行为变化趋势");
        
        Map<String, Object> behaviorData = new HashMap<>();
        
        // 季度下载量峰值
        List<Map<String, Object>> quarterlyDownloadPeak = getQuarterlyDownloadPeak();
        behaviorData.put("quarterlyDownloadPeak", quarterlyDownloadPeak);
        
        // 季度调用量峰值
        List<Map<String, Object>> quarterlyCallPeak = getQuarterlyCallPeak();
        behaviorData.put("quarterlyCallPeak", quarterlyCallPeak);
        
        // 不同资源类型使用偏好
        List<Map<String, Object>> resourceTypePreference = getResourceTypePreference();
        behaviorData.put("resourceTypePreference", resourceTypePreference);
        
        log.info("用户行为变化分析完成");
        return behaviorData;
    }
    
    /**
     * 获取热门资源排行
     * 业务含义：统计9年累计下载和调用Top10资源
     */
    public Map<String, Object> getPopularResourcesRanking() {
        log.info("开始分析热门资源排行");
        
        Map<String, Object> rankingData = new HashMap<>();
        
        // 累计下载Top10
        List<Map<String, Object>> topDownloadResources = getTopDownloadResources(10);
        rankingData.put("topDownloadResources", topDownloadResources);
        
        // 累计调用Top10
        List<Map<String, Object>> topCallResources = getTopCallResources(10);
        rankingData.put("topCallResources", topCallResources);
        
        // 按部门统计热门资源
        List<Map<String, Object>> departmentPopularResources = getDepartmentPopularResources();
        rankingData.put("departmentPopularResources", departmentPopularResources);
        
        log.info("热门资源排行分析完成");
        return rankingData;
    }
    
    /**
     * 获取年度资源增长数据
     * 业务含义：统计每年新增的接口/库表/Excel数量
     */
    private List<Map<String, Object>> getYearlyResourceGrowth() {
        List<Map<String, Object>> yearlyData = new ArrayList<>();
        
        // 模拟数据，实际应该从数据库查询
        for (int year = 2015; year <= 2024; year++) {
            Map<String, Object> yearData = new HashMap<>();
            yearData.put("year", year);
            yearData.put("apiCount", getRandomCount(50, 200));
            yearData.put("dbCount", getRandomCount(30, 150));
            yearData.put("excelCount", getRandomCount(100, 500));
            yearData.put("totalCount", (Integer) yearData.get("apiCount") + 
                         (Integer) yearData.get("dbCount") + 
                         (Integer) yearData.get("excelCount"));
            yearlyData.add(yearData);
        }
        
        return yearlyData;
    }
    
    /**
     * 获取各部门资源贡献占比
     * 业务含义：统计各部门提供的资源数量占比
     */
    private List<Map<String, Object>> getDepartmentContribution() {
        List<Map<String, Object>> departmentData = new ArrayList<>();
        
        // 模拟数据，实际应该从数据库查询
        String[] departments = {"省统计局", "省民政厅", "省教育厅", "省卫健委", "省交通厅"};
        
        for (String department : departments) {
            Map<String, Object> deptData = new HashMap<>();
            deptData.put("department", department);
            deptData.put("resourceCount", getRandomCount(100, 1000));
            deptData.put("contributionRatio", getRandomRatio());
            departmentData.add(deptData);
        }
        
        return departmentData;
    }
    
    /**
     * 获取资源类型增长趋势
     * 业务含义：分析不同资源类型的增长趋势
     */
    private List<Map<String, Object>> getResourceTypeTrend() {
        List<Map<String, Object>> typeTrend = new ArrayList<>();
        
        String[] resourceTypes = {"API", "DB", "EXCEL"};
        
        for (String type : resourceTypes) {
            Map<String, Object> typeData = new HashMap<>();
            typeData.put("resourceType", type);
            
            List<Map<String, Object>> yearlyTrend = new ArrayList<>();
            for (int year = 2015; year <= 2024; year++) {
                Map<String, Object> yearData = new HashMap<>();
                yearData.put("year", year);
                yearData.put("count", getRandomCount(20, 300));
                yearlyTrend.add(yearData);
            }
            
            typeData.put("yearlyTrend", yearlyTrend);
            typeTrend.add(typeData);
        }
        
        return typeTrend;
    }
    
    /**
     * 获取季度下载量峰值
     * 业务含义：统计每个季度的下载量峰值
     */
    private List<Map<String, Object>> getQuarterlyDownloadPeak() {
        List<Map<String, Object>> quarterlyData = new ArrayList<>();
        
        // 模拟数据，实际应该从数据库查询
        for (int year = 2015; year <= 2024; year++) {
            for (int quarter = 1; quarter <= 4; quarter++) {
                Map<String, Object> quarterData = new HashMap<>();
                quarterData.put("year", year);
                quarterData.put("quarter", quarter);
                quarterData.put("downloadPeak", getRandomCount(1000, 10000));
                quarterData.put("avgDownload", getRandomCount(500, 5000));
                quarterlyData.add(quarterData);
            }
        }
        
        return quarterlyData;
    }
    
    /**
     * 获取季度调用量峰值
     * 业务含义：统计每个季度的接口调用量峰值
     */
    private List<Map<String, Object>> getQuarterlyCallPeak() {
        List<Map<String, Object>> quarterlyData = new ArrayList<>();
        
        // 模拟数据，实际应该从数据库查询
        for (int year = 2015; year <= 2024; year++) {
            for (int quarter = 1; quarter <= 4; quarter++) {
                Map<String, Object>> quarterData = new HashMap<>();
                quarterData.put("year", year);
                quarterData.put("quarter", quarter);
                quarterData.put("callPeak", getRandomCount(5000, 50000));
                quarterData.put("avgCall", getRandomCount(2000, 20000));
                quarterlyData.add(quarterData);
            }
        }
        
        return quarterlyData;
    }
    
    /**
     * 获取资源类型使用偏好
     * 业务含义：分析不同用户类型对不同资源类型的偏好
     */
    private List<Map<String, Object>> getResourceTypePreference() {
        List<Map<String, Object>> preferenceData = new ArrayList<>();
        
        // 模拟数据，实际应该从数据库查询
        String[] userTypes = {"企业用户", "科研机构", "政府部门", "个人用户"};
        String[] resourceTypes = {"API", "DB", "EXCEL"};
        
        for (String userType : userTypes) {
            Map<String, Object>> userPreference = new HashMap<>();
            userPreference.put("userType", userType);
            
            List<Map<String, Object>> typeUsage = new ArrayList<>();
            for (String resourceType : resourceTypes) {
                Map<String, Object>> typeData = new HashMap<>();
                typeData.put("resourceType", resourceType);
                typeData.put("usageCount", getRandomCount(100, 5000));
                typeData.put("preferenceRatio", getRandomRatio());
                typeUsage.add(typeData);
            }
            
            userPreference.put("typeUsage", typeUsage);
            preferenceData.add(userPreference);
        }
        
        return preferenceData;
    }
    
    /**
     * 获取累计下载Top10资源
     * 业务含义：统计9年累计下载量最高的10个资源
     */
    private List<Map<String, Object>> getTopDownloadResources(int limit) {
        List<Map<String, Object>> topResources = new ArrayList<>();
        
        // 模拟数据，实际应该从数据库查询
        String[] resourceNames = {
            "广东省GDP统计数据", "人口普查数据", "企业注册信息", 
            "交通流量数据", "教育统计数据", "医疗资源分布",
            "环境监测数据", "就业统计信息", "房地产数据", "金融统计数据"
        };
        
        for (int i = 0; i < Math.min(limit, resourceNames.length); i++) {
            Map<String, Object>> resource = new HashMap<>();
            resource.put("rank", i + 1);
            resource.put("resourceName", resourceNames[i]);
            resource.put("downloadCount", getRandomCount(10000, 100000));
            resource.put("resourceType", i % 3 == 0 ? "EXCEL" : (i % 3 == 1 ? "API" : "DB"));
            resource.put("department", "省统计局");
            topResources.add(resource);
        }
        
        return topResources;
    }
    
    /**
     * 获取累计调用Top10资源
     * 业务含义：统计9年累计调用量最高的10个接口
     */
    private List<Map<String, Object>> getTopCallResources(int limit) {
        List<Map<String, Object>> topResources = new ArrayList<>();
        
        // 模拟数据，实际应该从数据库查询
        String[] apiNames = {
            "企业注册信息查询接口", "人口数据查询接口", "GDP数据查询接口",
            "交通数据查询接口", "教育数据查询接口", "医疗数据查询接口",
            "环境数据查询接口", "就业数据查询接口", "房地产数据查询接口", "金融数据查询接口"
        };
        
        for (int i = 0; i < Math.min(limit, apiNames.length); i++) {
            Map<String, Object>> resource = new HashMap<>();
            resource.put("rank", i + 1);
            resource.put("apiName", apiNames[i]);
            resource.put("callCount", getRandomCount(50000, 500000));
            resource.put("avgResponseTime", getRandomCount(100, 1000));
            resource.put("successRate", getRandomRatio());
            topResources.add(resource);
        }
        
        return topResources;
    }
    
    /**
     * 获取各部门热门资源
     * 业务含义：统计各部门的热门资源排行
     */
    private List<Map<String, Object>> getDepartmentPopularResources() {
        List<Map<String, Object>> departmentData = new ArrayList<>();
        
        String[] departments = {"省统计局", "省民政厅", "省教育厅"};
        
        for (String department : departments) {
            Map<String, Object>> deptData = new HashMap<>();
            deptData.put("department", department);
            deptData.put("topResources", getTopDownloadResources(5));
            departmentData.add(deptData);
        }
        
        return departmentData;
    }
    
    // 辅助方法
    private int getRandomCount(int min, int max) {
        return new Random().nextInt(max - min + 1) + min;
    }
    
    private double getRandomRatio() {
        return new Random().nextDouble();
    }
}
